package cn.stronglink.oil.video;

import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonArray;
import com.loopj.android.http.BaseJsonHttpResponseHandler;
import com.loopj.android.http.TextHttpResponseHandler;

import org.videolan.libvlc.IVLCVout;
import org.videolan.libvlc.LibVLC;
import org.videolan.libvlc.Media;
import org.videolan.libvlc.MediaPlayer;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

import cn.stronglink.oil.R;
import cn.stronglink.oil.user.User;
import cn.stronglink.oil.utils.HttpClientUtils;
import cz.msebera.android.httpclient.Header;


public class RTMPActivity extends AppCompatActivity implements IVLCVout.Callback {
    public final static String TAG = "MainActivity";
    private String mFilePath;
    private SurfaceView mSurface0, mSurface1, mSurface2, mSurface3;
    private SurfaceHolder holder0, holder1, holder2, holder3;
    private LibVLC libvlc;
    private MediaPlayer mMediaPlayer0 = null;
    private MediaPlayer mMediaPlayer1 = null;
    private MediaPlayer mMediaPlayer2 = null;
    private MediaPlayer mMediaPlayer3 = null;
    private int mVideoWidth;
    private int mVideoHeight;
    private JSONArray cameraArray;

    private FrameLayout fl_hint_0,fl_hint_1,fl_hint_2,fl_hint_3;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rtmp);
        mFilePath = "rtmp://202.69.69.180:443/webcast/bshdlive-pc";
//        Log.d(TAG, "Playing: " + mFilePath);
        initFramLayout();
        mSurface0 = findViewById(R.id.surface0);
        mSurface1 = findViewById(R.id.surface1);
        mSurface2 = findViewById(R.id.surface2);
        mSurface3 = findViewById(R.id.surface3);
        mSurface0.requestFocus();
        mSurface1.requestFocus();
        mSurface2.requestFocus();
        mSurface3.requestFocus();
        holder0 = mSurface0.getHolder();
        holder1 = mSurface1.getHolder();
        holder2 = mSurface2.getHolder();
        holder3 = mSurface3.getHolder();
        initMediaplayer();


    }

    private void initFramLayout() {
        fl_hint_0 = findViewById(R.id.fl_hint_0);
        fl_hint_1 = findViewById(R.id.fl_hint_1);
        fl_hint_2 = findViewById(R.id.fl_hint_2);
        fl_hint_3 = findViewById(R.id.fl_hint_3);
    }

    private void initMediaplayer() {
        ArrayList<String> options = new ArrayList<String>();
        //options.add("--subsdec-encoding <encoding>");
        options.add("--aout=opensles");
        options.add("--audio-time-stretch"); // time stretching
        options.add("-vvv"); // verbosity
        libvlc = new LibVLC(this, options);
        mMediaPlayer0 = new MediaPlayer(libvlc);
        mMediaPlayer1 = new MediaPlayer(libvlc);
        mMediaPlayer2 = new MediaPlayer(libvlc);
        mMediaPlayer3 = new MediaPlayer(libvlc);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
//        setSize(holder0,mSurface0,mVideoWidth, mVideoHeight);
//        setSize(holder1,mSurface1,mVideoWidth, mVideoHeight);
//        setSize(holder2,mSurface2,mVideoWidth, mVideoHeight);
//        setSize(holder3,mSurface3,mVideoWidth, mVideoHeight);
    }

    @Override
    protected void onResume() {
        super.onResume();
//        createPlayer(holder0,mFilePath,mSurface0);
        getVideoUrls();
    }

    @Override
    protected void onPause() {
        super.onPause();
//        releasePlayer(mMediaPlayer0);
//        releasePlayer(mMediaPlayer1);
//        releasePlayer(mMediaPlayer2);
//        releasePlayer(mMediaPlayer3);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        releasePlayer(mMediaPlayer0);
        releasePlayer(mMediaPlayer1);
        releasePlayer(mMediaPlayer2);
        releasePlayer(mMediaPlayer3);
    }


    /**
     * Used to set size for SurfaceView
     *
     * @param width
     * @param height
     */
    private void setSize(SurfaceHolder holder, SurfaceView mSurface, int width, int height) {
        mVideoWidth = width;
        mVideoHeight = height;
        if (mVideoWidth * mVideoHeight <= 1)
            return;

        if (holder == null || mSurface == null)
            return;

        int w = getWindow().getDecorView().getWidth();
        int h = getWindow().getDecorView().getHeight();
        boolean isPortrait = getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
        if (w > h && isPortrait || w < h && !isPortrait) {
            int i = w;
            w = h;
            h = i;
        }

        float videoAR = (float) mVideoWidth / (float) mVideoHeight;
        float screenAR = (float) w / (float) h;

        if (screenAR < videoAR)
            h = (int) (w / videoAR);
        else
            w = (int) (h * videoAR);

        holder.setFixedSize(mVideoWidth, mVideoHeight);
        LayoutParams lp = mSurface.getLayoutParams();
        lp.width = w;
        lp.height = h;
        mSurface.setLayoutParams(lp);
        mSurface.invalidate();
    }

    /**
     * Creates MediaPlayer and plays video
     *
     * @param media
     */
    private void createPlayer(SurfaceHolder holder, String media, SurfaceView mSurface, MediaPlayer mMediaPlayer) {
//        releasePlayer();
        try {
//            if (media.length() > 0) {
//                Toast toast = Toast.makeText(this, media, Toast.LENGTH_LONG);
//                toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0,
//                        0);
//                toast.show();
//            }

            // Create LibVLC
            // TODO: make this more robust, and sync with audio demo

            holder.setKeepScreenOn(true);

            // Creating media player
//            mMediaPlayer = new MediaPlayer(libvlc);
            mMediaPlayer.setEventListener(mPlayerListener);

            // Seting up video output
            final IVLCVout vout = mMediaPlayer.getVLCVout();
            vout.setVideoView(mSurface);
            //vout.setSubtitlesView(mSurfaceSubtitles);
            vout.addCallback(this);
            vout.attachViews();

            Media m = new Media(libvlc, Uri.parse(media));
            mMediaPlayer.setMedia(m);
            mMediaPlayer.play();
        } catch (Exception e) {
            Toast.makeText(this, "Error in creating player!", Toast
                    .LENGTH_LONG).show();
        }
    }

    private void releasePlayer(MediaPlayer mMediaPlayer) {
        mMediaPlayer.stop();
        IVLCVout vout = mMediaPlayer.getVLCVout();
        vout.removeCallback(this);
        vout.detachViews();
        holder0 = null;
        holder1 = null;
        holder2 = null;
        holder3 = null;
        mMediaPlayer = null;
        mVideoWidth = 0;
        mVideoHeight = 0;
        if (libvlc == null) return;
        libvlc.release();
        libvlc = null;
    }

    /**
     * Registering callbacks
     */
    private MediaPlayer.EventListener mPlayerListener = new MyPlayerListener(this);

    @Override
    public void onNewLayout(IVLCVout vout, int width, int height, int visibleWidth, int visibleHeight, int sarNum, int sarDen) {
        if (width * height == 0)
            return;

        // store video size
        mVideoWidth = width;
        mVideoHeight = height;
        setSize(holder0, mSurface0, mVideoWidth, mVideoHeight);
        setSize(holder1, mSurface1, mVideoWidth, mVideoHeight);
        setSize(holder2, mSurface2, mVideoWidth, mVideoHeight);
        setSize(holder3, mSurface3, mVideoWidth, mVideoHeight);
    }

    @Override
    public void onSurfacesCreated(IVLCVout vout) {

    }

    @Override
    public void onSurfacesDestroyed(IVLCVout vout) {

    }

    @Override
    public void onHardwareAccelerationError(IVLCVout vlcVout) {
        Log.e(TAG, "Error with hardware acceleration");
        this.releasePlayer(mMediaPlayer0);
        this.releasePlayer(mMediaPlayer1);
        this.releasePlayer(mMediaPlayer2);
        this.releasePlayer(mMediaPlayer3);
        Toast.makeText(this, "Error with hardware acceleration", Toast.LENGTH_LONG).show();
    }

    public void onMapBtnClicked(View view) {
        finish();
    }

    private static class MyPlayerListener implements MediaPlayer.EventListener {
        private WeakReference<RTMPActivity> mOwner;

        public MyPlayerListener(RTMPActivity owner) {
            mOwner = new WeakReference<RTMPActivity>(owner);
        }

        @Override
        public void onEvent(MediaPlayer.Event event) {
            RTMPActivity player = mOwner.get();

            switch (event.type) {
                case MediaPlayer.Event.EndReached:
                    Log.d(TAG, "MediaPlayerEndReached");
                    break;
                case MediaPlayer.Event.Playing:
                case MediaPlayer.Event.Paused:
                case MediaPlayer.Event.Stopped:
                default:
                    break;
            }
        }
    }

    private void showCamera(JSONArray array) {

        String cameraHost = HttpClientUtils.CAMERA_HOST;
        for (int i = 0; i < array.size(); i++) {
            JSONObject object = array.getJSONObject(i);
            if (i > 3) return;
            if (object == null) continue;
            String camera = object.getString("ip");
            if (camera == null || camera.isEmpty()) continue;
            final String url = "rtmp://" + cameraHost + "/hls/" + camera;

            switch (i) {
                case 0:
                    fl_hint_0.setVisibility(View.GONE);
                    createPlayer(holder0, url, mSurface0, mMediaPlayer0);
                    findViewById(R.id.fullscreen0).setVisibility(View.VISIBLE);
                    findViewById(R.id.fullscreen0).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            startActivity(new Intent(RTMPActivity.this, RTMPSingleActivity.class).putExtra("url", url));
                            finish();
                        }
                    });
                    break;
                case 1:
                    fl_hint_1.setVisibility(View.GONE);
                    createPlayer(holder1, url, mSurface1, mMediaPlayer1);
                    findViewById(R.id.fullscreen1).setVisibility(View.VISIBLE);
                    findViewById(R.id.fullscreen1).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            startActivity(new Intent(RTMPActivity.this, RTMPSingleActivity.class).putExtra("url", url));
                            finish();
                        }
                    });
                    break;
                case 2:
                    fl_hint_2.setVisibility(View.GONE);
                    createPlayer(holder2, url, mSurface2, mMediaPlayer2);
                    findViewById(R.id.fullscreen2).setVisibility(View.VISIBLE);
                    findViewById(R.id.fullscreen2).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            startActivity(new Intent(RTMPActivity.this, RTMPSingleActivity.class).putExtra("url", url));
                            finish();
                        }
                    });
                    break;
                case 3:
                    fl_hint_3.setVisibility(View.GONE);
                    createPlayer(holder3, url, mSurface3, mMediaPlayer3);
                    findViewById(R.id.fullscreen3).setVisibility(View.VISIBLE);
                    findViewById(R.id.fullscreen3).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            startActivity(new Intent(RTMPActivity.this, RTMPSingleActivity.class).putExtra("url", url));
                            finish();
                        }
                    });
                    break;
            }
        }
    }

    private void getVideoUrls() {
//        createPlayer(holder0, mFilePath, mSurface0,mMediaPlayer0);
//        createPlayer(holder1, mFilePath, mSurface1,mMediaPlayer1);
//        createPlayer(holder2, mFilePath, mSurface2,mMediaPlayer2);
//        createPlayer(holder3, mFilePath, mSurface3,mMediaPlayer3);


        try {
            User user = User.getInstance();
            String roomCode = user.getRoomCode();
            HttpClientUtils.getVideoUrlList(roomCode, new TextHttpResponseHandler() {

                @Override
                public void onFailure(int i, Header[] headers, String s, Throwable throwable) {

                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, String responseString) {
                    Log.e("onSuccess: ", responseString);
                    final JSONObject result = JSON.parseObject(responseString);
                    if (result.getIntValue("httpCode") == 200) {
                        JSONArray array = result.getJSONArray("data");
                        if (array != null && array.size() > 0) {
                            showCamera(array);
                        }
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

        mSurface0.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mMediaPlayer0.isPlaying()) {
                    mMediaPlayer0.pause();
                    findViewById(R.id.pause0).setVisibility(View.VISIBLE);
                } else {
                    mMediaPlayer0.play();
                    findViewById(R.id.pause0).setVisibility(View.GONE);
                }

            }
        });
        mSurface1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mMediaPlayer1.isPlaying()) {
                    mMediaPlayer1.pause();
                    findViewById(R.id.pause1).setVisibility(View.VISIBLE);
                } else {
                    mMediaPlayer1.play();
                    findViewById(R.id.pause1).setVisibility(View.GONE);
                }
            }
        });
        mSurface2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mMediaPlayer2.isPlaying()) {
                    mMediaPlayer2.pause();
                    findViewById(R.id.pause2).setVisibility(View.VISIBLE);
                } else {
                    mMediaPlayer2.play();
                    findViewById(R.id.pause2).setVisibility(View.GONE);
                }

            }
        });
        mSurface3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mMediaPlayer3.isPlaying()) {
                    mMediaPlayer3.pause();
                    findViewById(R.id.pause3).setVisibility(View.VISIBLE);
                } else {
                    mMediaPlayer3.play();
                    findViewById(R.id.pause3).setVisibility(View.GONE);
                }
            }
        });
    }
}